﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BestCode.Creds.Data.MapHelper;
using BestCode.Creds.Dto;
using BestCode.Creds.Entities;
using BestCode.DataAccess.Hibernate;
using BestCode.DataAccess.Hibernate.Helpers;


namespace BestCode.Creds.Data
{
    public class SummaryDao : DaoBase<object>, ISummaryDao
    {
        public IList<SummaryDto> GetSummary(int entityId = 0)
        {
            string sql = @"declare @entityId int = :entityId
                            
                            select 
                              EntityCode = e.Code,
                              EntityName = e.Name,
  
                              ChildEntityName = ech.Name,  
                              TotalEnabled = SUM(case when fd.IsEnabled = 1 then 1 else 0 end) ,
                              TotalDisabled = SUM(case when fd.IsEnabled = 0 then 1 else 0 end),  
                              Total = count(*),
  
                              AmountEnabled = SUM(case when fd.IsEnabled = 1 then 1 else 0 end) *  (case when (ech.CredentialCost is not null) AND (ech.CredentialCost <> 0)  then ech.CredentialCost else e.CredentialCost end),
                              AmountDisabled = SUM(case when fd.IsEnabled = 0 then 1 else 0 end) * (case when (ech.CredentialCost is not null) AND (ech.CredentialCost <> 0)  then ech.CredentialCost else e.CredentialCost end),
  
                              AnverseFacePath = tanverse.FaceImagePath,
                              ReverseFacePath = treverse.FaceImagePath,
  
                              AnverseFace = null,
                              ReverseFace = null
  
                            from Entity e
                            left join EntityChild ech on ech.EntityId = e.EntityId
                            left join FieldDefinition fd on fd.EntityChildId = ech.EntityChildId
                            left join Template tanverse on tanverse.TemplateId = e.AnverseTemplateId
                            left join Template treverse on treverse.TemplateId = e.ReverseTemplateId
                            where e.EntityId = @entityId or @entityId = 0

                            group by e.Code, e.Name, e.CredentialCost, ech.CredentialCost, ech.Name, tanverse.FaceImagePath, treverse.FaceImagePath
                            order by e.Code, ech.Name";

            var query = Session.CreateSQLQuery(sql);
            query.SetInt32("entityId", entityId);
            return query.ListBeanTransformer<SummaryDto>();
        }

    }
}
